﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace PhilWicklund.com.FacebookParts.Data
{
	public class FacebookSettings: DataObjectBase
	{
        private static string propertyBagKey = PropertyBagKeys.FacebookSettings.ToString();

        public string APIKey;

		public FacebookSettings() { }

		public FacebookSettings(
            string APIKey)
		{
            this.APIKey = APIKey;
		}

		public static FacebookSettings GetSettings(string webUrl)
		{
			FacebookSettings settings = new FacebookSettings();
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite site = new SPSite(webUrl))
				{
					string relativeWebUrl = "";
					if (site.Url != webUrl) // NOT Root Web
						relativeWebUrl = webUrl.Substring(site.Url.Length + 1);
					using (SPWeb web = site.OpenWeb(relativeWebUrl))
					{

						if (web.Properties.ContainsKey(propertyBagKey))
						{
							string settingsXml = web.Properties[propertyBagKey];
							settings = (FacebookSettings)FacebookSettings.Deserialize(
								typeof(FacebookSettings), settingsXml);
						}
						else
						{
							settings = new FacebookSettings(String.Empty);
						}
					}
				}
			});
			return settings;
		} 

		public static void SetSettings(SPWeb web, FacebookSettings settings)
		{
				web.AllowUnsafeUpdates = true;
				settings = InstanciateDefaultsIfNeccessary(settings);
				if (web.Properties.ContainsKey(propertyBagKey))
				{

					web.Properties[propertyBagKey] = settings.ToXml();
					web.Properties.Update();
				}
				else
				{
					web.Properties.Add(propertyBagKey, settings.ToXml());
					web.Properties.Update();
				}
				web.AllowUnsafeUpdates = false;
		}

		public static FacebookSettings InstanciateDefaultsIfNeccessary(FacebookSettings settings)
		{
            if (settings.APIKey == null)
                settings.APIKey = "";
			
			return settings;
		}

		public override string ToString()
		{
			return this.ToXml();
		}
	}
}
